package org.hrhr74.utils;


import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements  ILock{

    private String name;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private StringRedisTemplate stringRedisTemplate;


    private static final String keyPrefix = "lock:";
    private static final String UUIDPrefix = UUID.randomUUID().toString(true) + "-";


    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static{
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeOutSec) {

        String value = UUIDPrefix + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(keyPrefix + name,
                value
                , timeOutSec, TimeUnit.SECONDS);

        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock() {
//        String threadId = UUIDPrefix + Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(keyPrefix + name);
//        if(threadId.equals(id)) {
//            stringRedisTemplate.delete(keyPrefix + name);
//        }

       stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(keyPrefix + name)
       ,UUIDPrefix + Thread.currentThread().getId());
    }



}
